const youzanyun = require('youzanyun-sdk');
const assert = require('assert');

class YZAPI {
    static async _baseApi(apiName, version, token, params) {
        const res = await youzanyun.client.call({
            api: apiName,
            version,
            token,
            params,
        });

        let resp = res.data;

        assert(resp, '错误的返回');
        assert(resp.code == 200, `返回错误码：${resp.code}, trace_id=${resp.trace_id}`);
        assert(resp.data, '无效的返回数据');
        return resp.data;
    }

    /**
     * 批量加密
     * @param {*} yzToken
     * @param {*} plaintextArray
     * @returns
     */
    static async batchEncrypt(yzToken, plaintextArray) {
        const params = {
            sources: plaintextArray,
        };

        let texts = await this._baseApi('youzan.cloud.secret.encrypt.batch', '1.0.0', yzToken, params);
        let res = [];
        for (let str of plaintextArray) {
            res.push(texts[str]);
        }
        return res;
    }

    /**
     * 批量解密
     * @param {*} yzToken
     * @param {*} ciphertextArray
     * @returns
     */
    static async batchDecrypt(yzToken, ciphertextArray) {
        const params = {
            sources: ciphertextArray,
        };

        let texts = await this._baseApi('youzan.cloud.secret.decrypt.batch', '1.0.0', yzToken, params);
        let res = [];
        for (let str of ciphertextArray) {
            res.push(texts[str]);
        }
        return res;
    }

    /**
     * 批量判断
     * @param {*} yzToken
     * @param {*} ciphertextArray
     * @returns
     */
    static async batchQueryEncryptStatus(yzToken, ciphertextArray) {
        const params = {
            request: { sources: ciphertextArray },
        };

        let data = await this._baseApi('youzan.cloud.secret.verify.isencryptlist', '1.0.0', yzToken, params);
        return data.is_encrypt;
    }

    static async singleEncrypt(yzToken, plaintext) {
        const params = {
            source: plaintext,
        };

        return await this._baseApi('youzan.cloud.secret.encrypt.single', '1.0.0', yzToken, params);
    }

    static async singleDecrypt(yzToken, ciphertext) {
        const params = {
            source: ciphertext,
        };

        return await this._baseApi('youzan.cloud.secret.decrypt.single', '1.0.0', yzToken, params);
    }

    static async singleQueryEncryptStatus(yzToken, ciphertext) {
        const params = {
            secret_key_single_encrypt_query_request: { source: ciphertext },
        };

        let data = await this._baseApi('youzan.cloud.secret.verify.isencrypt', '1.0.0', yzToken, params);
        return data.is_encrypt;
    }
}

module.exports = YZAPI;
